package com.szewec.ps.ui.road.facilities.intersection.task;

import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivitySlowLaneBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.response.ResponseData;
import com.szewec.ps.myinterface.BindEditTextViewValue;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.road.facilities.intersection.task.enums.RoadEnums;
import com.szewec.ps.ui.road.facilities.intersection.task.model.SlowLane;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.BeanUtils;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.ViewUtils;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;
import com.szewec.ps.util.okhttp.OkHttp;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public class SlowLaneActivity extends BaseMediaPickerActivity implements BindEditTextViewValue {

    private ActivitySlowLaneBinding binding;

    private String flag;

    private final List<String> divideTypeList = RoadEnums.SlowLaneDivideType.getEnumValueList();
    private final List<String> paveTypeList = RoadEnums.PaveType.getEnumValueList();

    //接收的对象
    private SlowLane slowLane = new SlowLane();
    //上传的对象
    private SlowLane newSlowLane = new SlowLane();

    // 照片上传数组
    private List<String> photoSketchUploadIdArr = new ArrayList<>();
    // 照片文件数组
    private ArrayList<MediaFile> photoSketchFileArr = new ArrayList<>();
    // 图片适配器
    private CustomPickerAdapterShowAndEdit photoSketchAdapter;
    // 移除的图片ID数组
    private List<String> deletePhotoIdArr = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_slow_lane);
        ButterKnife.bind(this);
        Bundle presentValue = getIntent().getExtras();
        PresentValue<SlowLane> value = (PresentValue<SlowLane>) presentValue.getSerializable(Constants.EXTRA_KEY.ENTRANCE_ROAD);
        flag = value.getFlag();
        slowLane = value.getT();

        initTitleBar();
        initSelect();
        initViewFile();
        if (flag.equals(Constants.PRESENT_VALUE_FLAG.EDIT)) {
            setInputData();
        }
    }

    private void initTitleBar() {
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(v -> {
            saveData();
            CommonUtils.showIsSave(SlowLaneActivity.this, this::upTo);
        });
        binding.titleBar.setRightLayoutVisibility(View.VISIBLE);
        binding.titleBar.setRightTextVisibility(View.VISIBLE);
        binding.titleBar.setRightTextClickListener(v -> {
            saveData();
            if (BeanUtils.comparisonOutside(this.slowLane, newSlowLane)) {
                BamToast.showText(this, Constants.ErrorMsg.NOT_UPDATE, false);
                return;
            }
            upTo();
        });
    }

    private void initSelect() {
        binding.itDivideType.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, divideTypeList, binding.itDivideType.getSelectTextView(), (view, index) ->
                    binding.itDivideType.setValue(divideTypeList.get(index)));
        });
        binding.itSidewalkPaveType.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, paveTypeList, binding.itSidewalkPaveType.getSelectTextView(), (view, index) -> {
                if (paveTypeList.get(index).equals(RoadEnums.PaveType.OTHER.getValue())) {
                    binding.itSidewalkPaveTypeOther.setVisibility(View.VISIBLE);
                } else {
                    binding.itSidewalkPaveTypeOther.setVisibility(View.GONE);
                }
                binding.itSidewalkPaveType.setValue(paveTypeList.get(index));
            });
        });
        binding.itBicycleLanePaveType.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, paveTypeList, binding.itBicycleLanePaveType.getSelectTextView(), (view, index) -> {
                if (paveTypeList.get(index).equals(RoadEnums.PaveType.OTHER.getValue())) {
                    binding.itBicycleLanePaveTypeOther.setVisibility(View.VISIBLE);
                } else {
                    binding.itBicycleLanePaveTypeOther.setVisibility(View.GONE);
                }
                binding.itBicycleLanePaveType.setValue(paveTypeList.get(index));
            });
        });
    }

    private void setInputData() {
        binding.itDivideType.setValue(RoadEnums.SlowLaneDivideType.getValueByKey(slowLane.getDivideType()));
        BeanUtils.stripTrailingZeros(slowLane);
        binding.itSidewalkWidth.setValue(slowLane.getSidewalkWidth());
        binding.itBicycleLaneWidth.setValue(slowLane.getBicycleLaneWidth());

        String sidewalkPaveType = slowLane.getSidewalkPaveType();
        if (RoadEnums.PaveType.getKeyByValue(sidewalkPaveType) == null) {
            binding.itSidewalkPaveTypeOther.setVisibility(View.VISIBLE);
            binding.itSidewalkPaveTypeOther.setValue(sidewalkPaveType);
            sidewalkPaveType = RoadEnums.PaveType.OTHER.getValue();
        }
        binding.itSidewalkPaveType.setValue(sidewalkPaveType);

        String bicycleLanePaveType = slowLane.getBicycleLanePaveType();
        if (RoadEnums.PaveType.getKeyByValue(bicycleLanePaveType) == null) {
            binding.itBicycleLanePaveTypeOther.setVisibility(View.VISIBLE);
            binding.itBicycleLanePaveTypeOther.setValue(bicycleLanePaveType);
            bicycleLanePaveType = RoadEnums.PaveType.OTHER.getValue();
        }
        binding.itBicycleLanePaveType.setValue(bicycleLanePaveType);

        binding.itDivideWidth.setValue(slowLane.getDivideWidth());
    }

    // 设置照片
    private void initViewFile() {
        // 初始化照片适配器
        photoSketchAdapter = initTypeMediaRecyclerView(photoSketchUploadIdArr, photoSketchFileArr,
                binding.photoSketchSketchRV, true, false, true, deletePhotoIdArr);

        // 先根据fileId查询附件数据
        if (!CollectionUtils.isEmpty(slowLane.getAddIds())) {
            requestFilesByIds(slowLane.getAddIds(), this::initAdapterData);
        }
        // 根据业务ID查询附件信息
        else if (StringUtils.isNotEmpty(slowLane.getId())) {
            requestFiles(FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_INTERSECTION_SLOW_LANE_FILE_BIZ_TYPE, slowLane.getId(), this::initAdapterData);
        }
    }

    // 往照片适配器里面设置图片显示
    private void initAdapterData(List<MediaFile> mediaFileList) {
        if (CollectionUtils.isEmpty(mediaFileList)) {
            return;
        }
        photoSketchUploadIdArr.clear();
        photoSketchFileArr.clear();
        // 添加到文件数组
        photoSketchFileArr.addAll(mediaFileList);
        for (MediaFile mediaFile : photoSketchFileArr) {
            photoSketchUploadIdArr.add(mediaFile.getId());
        }
        // 设置适配器数据源
        photoSketchAdapter.setmMediaFileList(mediaFileList);
    }

    /**
     * 导流走新增还是修改
     */
    private void upTo() {
        if (flag.equals(Constants.PRESENT_VALUE_FLAG.ADD)) {
            postData();
        } else if (flag.equals(Constants.PRESENT_VALUE_FLAG.EDIT)) {
            putData();
        }
    }

    //保存数据到对象
    private void saveData() {

        BeanUtils.copyObj(this.slowLane, this.newSlowLane);

        newSlowLane.setDivideType(RoadEnums.SlowLaneDivideType.getKeyByValue(binding.itDivideType.getStringValue()));
        newSlowLane.setSidewalkWidth(binding.itSidewalkWidth.getBigDecimalValue());
        newSlowLane.setBicycleLaneWidth(binding.itBicycleLaneWidth.getBigDecimalValue());
        newSlowLane.setAddIds(photoSketchUploadIdArr);
        newSlowLane.setRemoveIds(deletePhotoIdArr);
        String sidewalkPaveType = binding.itSidewalkPaveType.getStringValue();
        if (RoadEnums.PaveType.OTHER.getValue().equals(sidewalkPaveType)) {
            sidewalkPaveType = binding.itSidewalkPaveTypeOther.getStringValue();
        }
        newSlowLane.setSidewalkPaveType(sidewalkPaveType);
        //非机动车道铺面类型
        String bicycleLanePaveType = binding.itBicycleLanePaveType.getStringValue();
        if (RoadEnums.PaveType.OTHER.getValue().equals(bicycleLanePaveType)) {
            bicycleLanePaveType = binding.itBicycleLanePaveTypeOther.getStringValue();
        }
        newSlowLane.setBicycleLanePaveType(bicycleLanePaveType);
        newSlowLane.setDivideWidth(binding.itDivideWidth.getBigDecimalValue());
    }

    /**
     * 存入后台
     */
    private void postData() {
        OkHttp.post("/tpms-plan-service/api/slow-lane/", newSlowLane, result -> {
            ResponseData responseData = JSON.parseObject(result, ResponseData.class);
            if (responseData.getCode() == Constants.ResponseCode.SUCCESS) {
                newSlowLane = JSON.parseObject(responseData.getData().toString(), SlowLane.class);
                BamToast.showText(this, responseData.getMsg(), true);
                setDataFinish();
            } else {
                BamToast.showText(this, responseData.getMsg(), false);
            }
        });
    }

    //修改数据存入后台
    private void putData() {
        OkHttp.put("/tpms-plan-service/api/slow-lane/", newSlowLane, result -> {
            ResponseData responseData = JSON.parseObject(result, ResponseData.class);
            if (responseData.getCode() == Constants.ResponseCode.SUCCESS) {
                BamToast.showText(this, responseData.getMsg(), true);
                setDataFinish();
            } else {
                BamToast.showText(this, responseData.getMsg(), false);
            }
        });
    }

    private void setDataFinish() {
        Intent intent = new Intent();
        intent.putExtra(Constants.EXTRA_KEY.ENTRANCE_ROAD, this.newSlowLane);
        setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
        finish();
    }

    @Override
    public void setObjValue() {

    }

    @Override
    public boolean checkLinkedDataAndFiles() {
        return false;
    }

    //监听滑动
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return ViewUtils.dispatchTouchEvent(this, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_INTERSECTION_SLOW_LANE_FILE_BIZ_TYPE);
            }
        }
    }
}